/**
 * 一个页面应用，即一个完整的CURD操作页面引用一次
 * 内部操作建议打开对话框完成
 */

var app = {
    api : '/api/index.php?s=',
    md5_salt : '48024573fc3c5a35651c255a5daa43e9'
};

/**
 * Create a cookie with the given key and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain used when the cookie was set.
 *
 * @param String
 *            key The key of the cookie.
 * @param String
 *            value The value of the cookie.
 * @param Object
 *            options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. If a negative value is specified (e.g. a date in the past), the cookie will be deleted. If set to null or omitted, the cookie will be a session cookie and will not be retained when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 *
 * Get the value of a cookie with the given key.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String
 *            key The key of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
app.cookie = function(key, value, options) {
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = $.extend({}, options);
        if (value === null) {
            options.expires = -1;
        }
        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }
        return (document.cookie = [ encodeURIComponent(key), '=', options.raw ? String(value) : encodeURIComponent(String(value)), options.expires ? '; expires=' + options.expires.toUTCString() : '', options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join(''));
    }
    options = value || {};
    var result, decode = options.raw ? function(s) {
        return s;
    } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

/**
 * 本地数据存取接口
 * @param key 被存储数据的主键
 * @param val 被存储数据的值：如果没有传参数，为获取值；如果为null，则为删除数据
 * @return mixed
 */
app.store = function (key, val) {
    if(arguments.length === 0) return false;
    if(arguments.length === 1) return JSON.parse(window.localStorage.getItem(key));
    if(val == null) return window.localStorage.removeItem(key);
    return window.localStorage.setItem(key, JSON.stringify(val));
}

/**
 * 跳转
 * @param url
 */
app.jump = function (url) {
    window.location = url;
}

/**
 * 上传文件
 * @param array options 参数
 * @param string option[browse_button] 选择按钮
 * @param string option[exts] 支持的扩展名
 * @param string option[idField] 保存文件ID的输入域
 * @param string option[nameField] 保存文件ID的输入域
 * @param string option[max_file_size] 支持的文件最大尺寸,默认10m
 * @param string option[chunk_size] 切片大小，默认1m
 */
app.upload = function (options) {
    var defaults = {
        runtimes: "html5,flash,html4",
        browse_button: options.browse_button,
        max_file_size: "10mb",
        chunk_size: "1mb",
        unique_names: true,  // 上传的文件名是否唯一
        multi_selection: false,
        multipart: true,
        multipart_params: {},
        url: "/api/index.php?s=Sys/Upload/plsave",
        flash_swf_url: "/public/static/plupload/plupload.flash.swf",
        filters: [
            {title: "上传文件类型", extensions: options.exts ? options.exts : "jpg,jpeg,png,gif,mp4,zip"}
        ],
        preinit: {
            UploadFile: function (up, file) {
                up.settings.multipart_params = {sourceName: file.name};
            }
        },

        init: {
            FilesAdded: function (up, files) {
                plupload.each(files, function (file) {
                    up.start();
                });
            },

            UploadProgress: function (up, file) {
                $(options.nameField).val("上传进度:" + file.percent + "%");
            },

            Error: function (up, err) {
                layout.error("上传失败:" + err.message, '错误提示');
            },
            FileUploaded: function (up, file, info) {
                var result = info.response;
                var res = $.parseJSON(String(result));
                $(options.nameField).val(file.name);
                layout.message("上传成功!","成功提示");
                $(options.idField).val(res.fileId);
            }
        }
    }
    $.extend(defaults, options);
    (new plupload.Uploader(defaults)).init();
}

/**
 * 生成Combobox下拉选择控件
 * @param DOM|$ ele 元素
 * @param string api 数据接口
 * @param array param 参数，同easyui combox参数
 */
app.combobox = function (ele, api, param) {
    var opts = $.extend({
        url: app.api + api,
        method:'get',
        valueField:'id',
        textField:'title',
        multiple:false,
        panelHeight:'150px',
        labelPosition: 'top'
    }, param);
    $(ele).combobox(opts);
}

/**
 * 生成ComboTree 树形下拉选择控件
 * @param DOM|$ ele 元素
 * @param string api 数据接口
 * @param array param 参数，同easyui combotree参数
 */
app.combotree = function (ele, api, param) {
    var opts = $.extend({
        url: app.api + api,
        method:'get',
        valueField:'id',
        parentField:'pid',
        textField:'title',
        multiple:false,
        panelHeight:'150px',
        labelPosition: 'top'
    }, param);
    $(ele).combotree(opts);
}